package service

import (
	"center-platform/internal/controller/v1/user/entity"
	"center-platform/utils"
	"errors"
	"github.com/gin-gonic/gin"
)

type UserImpl interface {
	Login(c *gin.Context) (error, string)
	Register(c *gin.Context) error
	InfoById(id int) *entity.UserBasicInfoResponse
	Update(c *gin.Context) error
}

type UserService struct {
}

func (us *UserService) Register(c *gin.Context) error {
	var user entity.User
	err := c.BindJSON(&user)
	if err != nil {
		return err
	}
	err = user.Register()
	if err != nil {
		return err
	}
	return nil
}

func (us *UserService) Login(c *gin.Context) (error, string) {
	var user entity.User
	var Auth utils.Auth
	err := c.BindJSON(&user)
	if err != nil {
		return err, ""
	}
	err, res := user.GetInfoByPw(user.Email, user.Password)
	if err != nil {
		return err, ""
	}
	Auth.UserId = res.Id
	Auth.Email = res.Email
	token, err := Auth.GenerateToken()
	if err != nil {
		return err, ""
	}
	return nil, token
}

func (us *UserService) InfoById(id int) *entity.UserBasicInfoResponse {
	var user entity.User
	return user.GetInfoById(id)
}

func (us *UserService) Update(c *gin.Context) error {
	var user entity.UserUpdate
	var args []interface{}
	var update = make(map[string]interface{})
	var where = " true"
	err := c.BindJSON(&user)
	if err != nil {
		return err
	}
	if user.Id > 0 {
		where += " and id = ?"
		args = append(args, user.Id)
	} else {
		return errors.New("id 不能为空")
	}

	if user.Name != "" {
		update["name"] = user.Name
		args = append(args, user.Name)
	}

	if user.Email != "" {
		update["email"] = user.Email
		args = append(args, user.Email)
	}

	if user.Avatar != "" {
		update["avatar"] = user.Avatar
		args = append(args, user.Avatar)
	}

	if user.Status != 0 {
		update["status"] = user.Status
		args = append(args, user.Status)
	}

	err = user.Update(where, update, args...)
	if err != nil {
		return err
	}
	return nil
}
